import { useState, useEffect, useRef } from 'react';
import { useNavigate } from 'react-router-dom';
import { ArrowLeft } from 'lucide-react';
import { calculateAngleExact } from '../utils/canvasUtils';
import '../pages/GeometryModelView.css';
import './SpecialModelBase.css';
import './TriangleInteriorAngles.css';

/**
 * TriangleInteriorAngles 特殊模板
 * 演示三角形内角和：角1 + 角2 + 角3 = 180°
 * 功能：
 * 1. 顶部顶点可拖动
 * 2. 显示三个内角标注
 * 3. 显示角度值和内角和
 */

function TriangleInteriorAngles({ modelTitle }) {
  const navigate = useNavigate();
  const canvasRef = useRef(null);
  
  // 三角形的三个顶点（缩小尺寸）
  const [vertices, setVertices] = useState({
    top: { x: 400, y: 150 },      // 顶点A（可拖动）
    bottomLeft: { x: 200, y: 380 }, // 顶点B（固定）
    bottomRight: { x: 600, y: 380 } // 顶点C（固定）
  });
  
  const [dragging, setDragging] = useState(false);
  const [showCutLines, setShowCutLines] = useState(false);
  const [showFoldLines, setShowFoldLines] = useState(false);
  const [showFoldAnimation, setShowFoldAnimation] = useState(false);
  const [foldProgress, setFoldProgress] = useState(0);
  const [showAssemble, setShowAssemble] = useState(false);
  const [animationProgress, setAnimationProgress] = useState(0);

  // 计算角度（弧度转度数，四舍五入）
  const calculateAngle = (p1, vertex, p2) => {
    return Math.round(calculateAngleExact(p1, vertex, p2));
  };

  // 计算三个内角
  const angle1 = parseFloat(calculateAngle(vertices.bottomLeft, vertices.top, vertices.bottomRight)); // 顶角
  const angle2 = parseFloat(calculateAngle(vertices.top, vertices.bottomLeft, vertices.bottomRight)); // 左下角
  const angle3 = parseFloat(calculateAngle(vertices.bottomLeft, vertices.bottomRight, vertices.top)); // 右下角

  // 固定工作空间尺寸
  const WORKSPACE_WIDTH = 800;
  const WORKSPACE_HEIGHT = 500;

  // 绘制画布
  useEffect(() => {
    const canvas = canvasRef.current;
    if (!canvas) return;

    // 根据屏幕尺寸决定画布尺寸（保持 8:5 比例）
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    const isLandscape = windowWidth > windowHeight;
    let displayWidth, displayHeight;
    
    // 根据横竖屏选择参考尺寸
    const referenceSize = isLandscape ? windowHeight : windowWidth;
    
    if (referenceSize <= 375) {
      // 小屏幕：360x225
      displayWidth = 360;
      displayHeight = 225;
    } else if (referenceSize <= 560) {
      // 中等屏幕：根据参考尺寸线性插值
      // 从 360x225 到 560x350
      const ratio = (referenceSize - 375) / (560 - 375);
      displayWidth = Math.round(360 + ratio * (560 - 360));
      displayHeight = Math.round(225 + ratio * (350 - 225));
    } else {
      // 大屏幕：原始尺寸 800x500
      displayWidth = WORKSPACE_WIDTH;
      displayHeight = WORKSPACE_HEIGHT;
    }
    
    // 设置高DPI
    const dpr = window.devicePixelRatio || 1;
    canvas.width = displayWidth * dpr;
    canvas.height = displayHeight * dpr;
    canvas.style.width = `${displayWidth}px`;
    canvas.style.height = `${displayHeight}px`;
    
    const ctx = canvas.getContext('2d');
    ctx.scale(dpr, dpr);
    
    // 如果不是原始尺寸，需要整体缩放绘制内容
    if (displayWidth !== WORKSPACE_WIDTH) {
      const scale = displayWidth / WORKSPACE_WIDTH;
      ctx.scale(scale, scale);
    }
    
    // 清空画布
    ctx.clearRect(0, 0, WORKSPACE_WIDTH, WORKSPACE_HEIGHT);
    
    // 绘制背景
    ctx.fillStyle = '#ffffff';
    ctx.fillRect(0, 0, WORKSPACE_WIDTH, WORKSPACE_HEIGHT);

    const { top, bottomLeft, bottomRight } = vertices;

    // 只在非折叠模式下绘制原始三角形
    if (!showFoldLines && !showFoldAnimation) {
      // 绘制三角形填充
      ctx.fillStyle = 'rgba(33, 150, 243, 0.1)';
      ctx.beginPath();
      ctx.moveTo(top.x, top.y);
      ctx.lineTo(bottomLeft.x, bottomLeft.y);
      ctx.lineTo(bottomRight.x, bottomRight.y);
      ctx.closePath();
      ctx.fill();

      // 绘制三角形边（黑色）
      ctx.strokeStyle = '#000000';
      ctx.lineWidth = 3;
      ctx.beginPath();
      ctx.moveTo(top.x, top.y);
      ctx.lineTo(bottomLeft.x, bottomLeft.y);
      ctx.lineTo(bottomRight.x, bottomRight.y);
      ctx.closePath();
      ctx.stroke();
    }

    // 绘制角度弧线和标注（确保始终绘制内角）
    const drawAngleArc = (vertex, p1, p2, label) => {
      const radius = 40;
      
      // 计算角度起始和结束方向
      let angle1 = Math.atan2(p1.y - vertex.y, p1.x - vertex.x);
      let angle2 = Math.atan2(p2.y - vertex.y, p2.x - vertex.x);
      
      // 标准化角度到 [0, 2π)
      if (angle1 < 0) angle1 += 2 * Math.PI;
      if (angle2 < 0) angle2 += 2 * Math.PI;
      
      // 计算角度差，确保始终取内角（小于180度的角）
      let angleDiff = angle2 - angle1;
      if (angleDiff < 0) angleDiff += 2 * Math.PI;
      
      // 如果角度差大于180度，说明应该反向绘制（逆时针）
      const counterclockwise = angleDiff > Math.PI;
      
      // 绘制角度弧线
      ctx.strokeStyle = '#ff9800';
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.arc(vertex.x, vertex.y, radius, angle1, angle2, counterclockwise);
      ctx.stroke();

      // 计算内角的中间角度
      let midAngle;
      if (counterclockwise) {
        // 逆时针：从angle1往反方向到angle2
        const innerAngleDiff = 2 * Math.PI - angleDiff;
        midAngle = angle1 - innerAngleDiff / 2;
      } else {
        // 顺时针：从angle1到angle2
        midAngle = angle1 + angleDiff / 2;
      }
      
      // 绘制角标签
      const labelRadius = radius + 25;
      const labelX = vertex.x + Math.cos(midAngle) * labelRadius;
      const labelY = vertex.y + Math.sin(midAngle) * labelRadius;
      
      ctx.font = 'bold 20px Arial';
      ctx.fillStyle = '#ff9800';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText(label, labelX, labelY);
    };

    // 绘制三个角（在拼接模式或折叠模式下不绘制）
    if (!showAssemble && !showFoldLines && !showFoldAnimation) {
      drawAngleArc(top, bottomRight, bottomLeft, '∠1');
      drawAngleArc(bottomLeft, top, bottomRight, '∠2');
      drawAngleArc(bottomRight, bottomLeft, top, '∠3');
    }

    // 绘制裁切线（剪一剪）
    if (showCutLines) {
      // 计算三条边的中点
      const bottomMid = {
        x: (bottomLeft.x + bottomRight.x) / 2,
        y: (bottomLeft.y + bottomRight.y) / 2
      };
      const leftMid = {
        x: (top.x + bottomLeft.x) / 2,
        y: (top.y + bottomLeft.y) / 2
      };
      const rightMid = {
        x: (top.x + bottomRight.x) / 2,
        y: (top.y + bottomRight.y) / 2
      };

      // 绘制裁切线（虚线）
      ctx.strokeStyle = '#e74c3c';
      ctx.lineWidth = 2;
      ctx.setLineDash([8, 4]);

      // 第一条裁切线：底边中点到左侧边中点的连线
      ctx.beginPath();
      ctx.moveTo(bottomMid.x, bottomMid.y);
      ctx.lineTo(leftMid.x, leftMid.y);
      ctx.stroke();

      // 第二条裁切线：左侧边中点到右侧边中点的连线
      ctx.beginPath();
      ctx.moveTo(leftMid.x, leftMid.y);
      ctx.lineTo(rightMid.x, rightMid.y);
      ctx.stroke();

      ctx.setLineDash([]);

      // 绘制中点标记
      const drawMidPoint = (point) => {
        ctx.beginPath();
        ctx.arc(point.x, point.y, 5, 0, Math.PI * 2);
        ctx.fillStyle = '#e74c3c';
        ctx.fill();
        ctx.strokeStyle = '#fff';
        ctx.lineWidth = 2;
        ctx.stroke();
      };

      drawMidPoint(bottomMid);
      drawMidPoint(leftMid);
      drawMidPoint(rightMid);
    }

    // 绘制折一折裁切线和阴影三角形
    if (showFoldLines || showFoldAnimation) {
      // 计算左右边的中点
      const leftMid = {
        x: (top.x + bottomLeft.x) / 2,
        y: (top.y + bottomLeft.y) / 2
      };
      const rightMid = {
        x: (top.x + bottomRight.x) / 2,
        y: (top.y + bottomRight.y) / 2
      };
      const bottomY = bottomLeft.y;
      const leftFootX = leftMid.x;
      const rightFootX = rightMid.x;

      // 定义三个三角形的顶点
      const triangle1 = [top, leftMid, rightMid]; // 顶部三角形（角1）
      const triangle2 = [bottomLeft, leftMid, { x: leftFootX, y: bottomY }]; // 左下三角形（角2）
      const triangle3 = [bottomRight, rightMid, { x: rightFootX, y: bottomY }]; // 右下三角形（角3）
      
      // 定义中间的矩形区域
      const rectangle = [
        leftMid,
        rightMid,
        { x: rightFootX, y: bottomY },
        { x: leftFootX, y: bottomY }
      ];

      // 绘制翻折动画
      if (showFoldAnimation) {
        // 三角形2（左下）沿着左侧垂线翻折
        const tri2Rotated = triangle2.map(p => {
          // 围绕垂线（x = leftFootX）旋转
          const relativeX = p.x - leftFootX;
          const angle = Math.PI * foldProgress; // 0 到 180度
          return {
            x: leftFootX + relativeX * Math.cos(angle),
            y: p.y,
            z: relativeX * Math.sin(angle) // 用于判断前后关系
          };
        });

        // 三角形3（右下）沿着右侧垂线翻折
        const tri3Rotated = triangle3.map(p => {
          const relativeX = p.x - rightFootX;
          const angle = Math.PI * foldProgress;
          return {
            x: rightFootX + relativeX * Math.cos(angle),
            y: p.y,
            z: relativeX * Math.sin(angle)
          };
        });

        // 三角形1（顶部）沿着左右中点连线翻折
        const tri1Rotated = triangle1.map(p => {
          // 围绕连线旋转，连线的y坐标大致为leftMid.y（近似处理）
          const pivotY = (leftMid.y + rightMid.y) / 2;
          const relativeY = p.y - pivotY;
          const angle = Math.PI * foldProgress;
          return {
            x: p.x,
            y: pivotY + relativeY * Math.cos(angle),
            z: relativeY * Math.sin(angle)
          };
        });

        // 绘制三角形（根据z值判断是否可见）
        const drawTriangleWithShading = (vertices, color, alpha, angleLabel, angleVertex) => {
          ctx.fillStyle = color.replace('1)', `${alpha})`);
          ctx.beginPath();
          ctx.moveTo(vertices[0].x, vertices[0].y);
          ctx.lineTo(vertices[1].x, vertices[1].y);
          ctx.lineTo(vertices[2].x, vertices[2].y);
          ctx.closePath();
          ctx.fill();

          ctx.strokeStyle = '#9c27b0';
          ctx.lineWidth = 2;
          ctx.stroke();

          // 绘制角度标注（确保始终绘制内角）
          if (angleVertex !== undefined && angleLabel) {
            const v = vertices[angleVertex];
            const v1 = vertices[(angleVertex + 1) % 3];
            const v2 = vertices[(angleVertex + 2) % 3];
            
            const radius = 25;
            let a1 = Math.atan2(v1.y - v.y, v1.x - v.x);
            let a2 = Math.atan2(v2.y - v.y, v2.x - v.x);
            
            // 标准化角度到 [0, 2π)
            if (a1 < 0) a1 += 2 * Math.PI;
            if (a2 < 0) a2 += 2 * Math.PI;
            
            // 计算角度差，确保始终取内角
            let angleDiff = a2 - a1;
            if (angleDiff < 0) angleDiff += 2 * Math.PI;
            const counterclockwise = angleDiff > Math.PI;
            
            ctx.strokeStyle = color.replace('1)', '1)');
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.arc(v.x, v.y, radius, a1, a2, counterclockwise);
            ctx.stroke();

            // 计算内角的中间角度
            let midAngle;
            if (counterclockwise) {
              const innerAngleDiff = 2 * Math.PI - angleDiff;
              midAngle = a1 - innerAngleDiff / 2;
            } else {
              midAngle = a1 + angleDiff / 2;
            }
            
            const labelRadius = radius + 18;
            const labelX = v.x + Math.cos(midAngle) * labelRadius;
            const labelY = v.y + Math.sin(midAngle) * labelRadius;
            
            ctx.font = 'bold 16px Arial';
            ctx.fillStyle = color.replace('1)', '1)');
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText(angleLabel, labelX, labelY);
          }
        };

        // 根据翻折进度调整透明度
        const alpha = 0.3 + 0.2 * Math.abs(Math.sin(foldProgress * Math.PI));
        
        drawTriangleWithShading(tri2Rotated, 'rgba(255, 152, 0, 1)', alpha, '∠2', 0);
        drawTriangleWithShading(tri3Rotated, 'rgba(76, 175, 80, 1)', alpha, '∠3', 0);
        drawTriangleWithShading(tri1Rotated, 'rgba(33, 150, 243, 1)', alpha, '∠1', 0);
        
        // 绘制中间的灰色矩形区域
        ctx.fillStyle = 'rgba(200, 200, 200, 0.4)';
        ctx.beginPath();
        ctx.moveTo(rectangle[0].x, rectangle[0].y);
        ctx.lineTo(rectangle[1].x, rectangle[1].y);
        ctx.lineTo(rectangle[2].x, rectangle[2].y);
        ctx.lineTo(rectangle[3].x, rectangle[3].y);
        ctx.closePath();
        ctx.fill();
        
        ctx.strokeStyle = '#9c27b0';
        ctx.lineWidth = 2;
        ctx.stroke();

      } else {
        // 只显示裁切线时，绘制阴影三角形
        const drawShadowTriangle = (vertices, color, angleLabel, angleVertex) => {
          ctx.fillStyle = color;
          ctx.beginPath();
          ctx.moveTo(vertices[0].x, vertices[0].y);
          ctx.lineTo(vertices[1].x, vertices[1].y);
          ctx.lineTo(vertices[2].x, vertices[2].y);
          ctx.closePath();
          ctx.fill();

          ctx.strokeStyle = '#9c27b0';
          ctx.lineWidth = 2;
          ctx.stroke();

          // 绘制角度标注（确保始终绘制内角）
          if (angleVertex !== undefined && angleLabel) {
            const v = vertices[angleVertex];
            const v1 = vertices[(angleVertex + 1) % 3];
            const v2 = vertices[(angleVertex + 2) % 3];
            
            const radius = 25;
            let a1 = Math.atan2(v1.y - v.y, v1.x - v.x);
            let a2 = Math.atan2(v2.y - v.y, v2.x - v.x);
            
            // 标准化角度到 [0, 2π)
            if (a1 < 0) a1 += 2 * Math.PI;
            if (a2 < 0) a2 += 2 * Math.PI;
            
            // 计算角度差，确保始终取内角
            let angleDiff = a2 - a1;
            if (angleDiff < 0) angleDiff += 2 * Math.PI;
            const counterclockwise = angleDiff > Math.PI;
            
            // 使用饱和度更高的颜色
            const solidColor = color.replace('0.3)', '1)');
            ctx.strokeStyle = solidColor;
            ctx.lineWidth = 2;
            ctx.beginPath();
            ctx.arc(v.x, v.y, radius, a1, a2, counterclockwise);
            ctx.stroke();

            // 计算内角的中间角度
            let midAngle;
            if (counterclockwise) {
              const innerAngleDiff = 2 * Math.PI - angleDiff;
              midAngle = a1 - innerAngleDiff / 2;
            } else {
              midAngle = a1 + angleDiff / 2;
            }
            
            const labelRadius = radius + 18;
            const labelX = v.x + Math.cos(midAngle) * labelRadius;
            const labelY = v.y + Math.sin(midAngle) * labelRadius;
            
            ctx.font = 'bold 16px Arial';
            ctx.fillStyle = solidColor;
            ctx.textAlign = 'center';
            ctx.textBaseline = 'middle';
            ctx.fillText(angleLabel, labelX, labelY);
          }
        };

        drawShadowTriangle(triangle1, 'rgba(33, 150, 243, 0.3)', '∠1', 0);
        drawShadowTriangle(triangle2, 'rgba(255, 152, 0, 0.3)', '∠2', 0);
        drawShadowTriangle(triangle3, 'rgba(76, 175, 80, 0.3)', '∠3', 0);
        
        // 绘制中间的灰色矩形区域
        ctx.fillStyle = 'rgba(200, 200, 200, 0.4)';
        ctx.beginPath();
        ctx.moveTo(rectangle[0].x, rectangle[0].y);
        ctx.lineTo(rectangle[1].x, rectangle[1].y);
        ctx.lineTo(rectangle[2].x, rectangle[2].y);
        ctx.lineTo(rectangle[3].x, rectangle[3].y);
        ctx.closePath();
        ctx.fill();
        
        ctx.strokeStyle = '#9c27b0';
        ctx.lineWidth = 2;
        ctx.stroke();
      }

      // 绘制裁切线（虚线）
      if (!showFoldAnimation) {
        ctx.strokeStyle = '#9c27b0';
        ctx.lineWidth = 2;
        ctx.setLineDash([8, 4]);

        // 第一条裁切线：左右边中点的连线
        ctx.beginPath();
        ctx.moveTo(leftMid.x, leftMid.y);
        ctx.lineTo(rightMid.x, rightMid.y);
        ctx.stroke();

        // 第二条裁切线：左边中点向底边的垂线
        ctx.beginPath();
        ctx.moveTo(leftMid.x, leftMid.y);
        ctx.lineTo(leftFootX, bottomY);
        ctx.stroke();

        // 第三条裁切线：右边中点向底边的垂线
        ctx.beginPath();
        ctx.moveTo(rightMid.x, rightMid.y);
        ctx.lineTo(rightFootX, bottomY);
        ctx.stroke();

        ctx.setLineDash([]);

        // 绘制中点标记
        const drawMidPoint = (point) => {
          ctx.beginPath();
          ctx.arc(point.x, point.y, 5, 0, Math.PI * 2);
          ctx.fillStyle = '#9c27b0';
          ctx.fill();
          ctx.strokeStyle = '#fff';
          ctx.lineWidth = 2;
          ctx.stroke();
        };

        drawMidPoint(leftMid);
        drawMidPoint(rightMid);
        
        // 绘制垂足点标记
        drawMidPoint({ x: leftFootX, y: bottomY });
        drawMidPoint({ x: rightFootX, y: bottomY });
      }
    }

    // 绘制拼接动画
    if (showAssemble) {
      // 计算三条边的中点
      const bottomMid = {
        x: (bottomLeft.x + bottomRight.x) / 2,
        y: (bottomLeft.y + bottomRight.y) / 2
      };
      const leftMid = {
        x: (top.x + bottomLeft.x) / 2,
        y: (top.y + bottomLeft.y) / 2
      };
      const rightMid = {
        x: (top.x + bottomRight.x) / 2,
        y: (top.y + bottomRight.y) / 2
      };

      // 图1的三个顶点（顶部三角形）- 原始顶点是: top, rightMid, leftMid
      // 注意：剪一剪后，图1的三个顶点应该是 top, rightMid, leftMid（不是bottomMid）
      const piece1Vertices = [top, rightMid, leftMid];
      const rotationAngle = Math.PI * animationProgress; // 0 到 180度
      
      // 旋转函数：围绕rightMid旋转
      const rotatePoint = (point, center, angle) => {
        const dx = point.x - center.x;
        const dy = point.y - center.y;
        return {
          x: center.x + dx * Math.cos(angle) - dy * Math.sin(angle),
          y: center.y + dx * Math.sin(angle) + dy * Math.cos(angle)
        };
      };

      const rotatedPiece1 = piece1Vertices.map(v => rotatePoint(v, rightMid, rotationAngle));

      // 绘制旋转后的图1（顶部三角形）
      ctx.save();
      
      // 绘制填充
      ctx.fillStyle = 'rgba(255, 152, 0, 0.3)';
      ctx.beginPath();
      ctx.moveTo(rotatedPiece1[0].x, rotatedPiece1[0].y);
      ctx.lineTo(rotatedPiece1[1].x, rotatedPiece1[1].y);
      ctx.lineTo(rotatedPiece1[2].x, rotatedPiece1[2].y);
      ctx.closePath();
      ctx.fill();

      // 绘制边框
      ctx.strokeStyle = '#FF9800';
      ctx.lineWidth = 2;
      ctx.stroke();

      // 绘制角1标注（在旋转后的位置，确保始终绘制内角）
      const angle1Vertex = rotatedPiece1[0];
      const angle1P1 = rotatedPiece1[1];
      const angle1P2 = rotatedPiece1[2];

      // 绘制角1的弧线
      const radius = 30;
      let a1 = Math.atan2(angle1P1.y - angle1Vertex.y, angle1P1.x - angle1Vertex.x);
      let a2 = Math.atan2(angle1P2.y - angle1Vertex.y, angle1P2.x - angle1Vertex.x);
      
      // 标准化角度到 [0, 2π)
      if (a1 < 0) a1 += 2 * Math.PI;
      if (a2 < 0) a2 += 2 * Math.PI;
      
      // 计算角度差，确保始终取内角
      let angleDiff = a2 - a1;
      if (angleDiff < 0) angleDiff += 2 * Math.PI;
      const counterclockwise = angleDiff > Math.PI;
      
      ctx.strokeStyle = '#FF9800';
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.arc(angle1Vertex.x, angle1Vertex.y, radius, a1, a2, counterclockwise);
      ctx.stroke();

      // 计算内角的中间角度
      let midAngle;
      if (counterclockwise) {
        const innerAngleDiff = 2 * Math.PI - angleDiff;
        midAngle = a1 - innerAngleDiff / 2;
      } else {
        midAngle = a1 + angleDiff / 2;
      }
      
      const labelRadius = radius + 20;
      const labelX = angle1Vertex.x + Math.cos(midAngle) * labelRadius;
      const labelY = angle1Vertex.y + Math.sin(midAngle) * labelRadius;
      
      ctx.font = 'bold 18px Arial';
      ctx.fillStyle = '#FF9800';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText('∠1', labelX, labelY);

      ctx.restore();

      // 图2的三个顶点（左下三角形）
      const piece2Vertices = [bottomLeft, bottomMid, leftMid];
      
      // 计算平移向量：将bottomLeft（角2）移动到bottomRight（角3）
      const targetX = bottomRight.x;
      const targetY = bottomRight.y;
      const offsetX = (targetX - bottomLeft.x) * animationProgress;
      const offsetY = (targetY - bottomLeft.y) * animationProgress;

      // 绘制平移后的图2（左下三角形）
      ctx.save();
      
      // 绘制填充
      ctx.fillStyle = 'rgba(76, 175, 80, 0.3)';
      ctx.beginPath();
      ctx.moveTo(piece2Vertices[0].x + offsetX, piece2Vertices[0].y + offsetY);
      ctx.lineTo(piece2Vertices[1].x + offsetX, piece2Vertices[1].y + offsetY);
      ctx.lineTo(piece2Vertices[2].x + offsetX, piece2Vertices[2].y + offsetY);
      ctx.closePath();
      ctx.fill();

      // 绘制边框
      ctx.strokeStyle = '#4CAF50';
      ctx.lineWidth = 2;
      ctx.stroke();

      // 绘制角2标注（在平移后的位置，确保始终绘制内角）
      const angle2Vertex = {
        x: piece2Vertices[0].x + offsetX,
        y: piece2Vertices[0].y + offsetY
      };
      const angle2P1 = {
        x: piece2Vertices[1].x + offsetX,
        y: piece2Vertices[1].y + offsetY
      };
      const angle2P2 = {
        x: piece2Vertices[2].x + offsetX,
        y: piece2Vertices[2].y + offsetY
      };

      // 绘制角2的弧线
      let a1_2 = Math.atan2(angle2P2.y - angle2Vertex.y, angle2P2.x - angle2Vertex.x);
      let a2_2 = Math.atan2(angle2P1.y - angle2Vertex.y, angle2P1.x - angle2Vertex.x);
      
      // 标准化角度到 [0, 2π)
      if (a1_2 < 0) a1_2 += 2 * Math.PI;
      if (a2_2 < 0) a2_2 += 2 * Math.PI;
      
      // 计算角度差，确保始终取内角
      let angleDiff2 = a2_2 - a1_2;
      if (angleDiff2 < 0) angleDiff2 += 2 * Math.PI;
      const counterclockwise2 = angleDiff2 > Math.PI;
      
      ctx.strokeStyle = '#4CAF50';
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.arc(angle2Vertex.x, angle2Vertex.y, radius, a1_2, a2_2, counterclockwise2);
      ctx.stroke();

      // 计算内角的中间角度
      let midAngle2;
      if (counterclockwise2) {
        const innerAngleDiff2 = 2 * Math.PI - angleDiff2;
        midAngle2 = a1_2 - innerAngleDiff2 / 2;
      } else {
        midAngle2 = a1_2 + angleDiff2 / 2;
      }
      
      const labelX2 = angle2Vertex.x + Math.cos(midAngle2) * labelRadius;
      const labelY2 = angle2Vertex.y + Math.sin(midAngle2) * labelRadius;
      
      ctx.font = 'bold 18px Arial';
      ctx.fillStyle = '#4CAF50';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText('∠2', labelX2, labelY2);

      ctx.restore();

      // 绘制角3（在原位置，确保始终绘制内角）
      ctx.save();
      
      // 角3的顶点位置
      const angle3Vertex = bottomRight;
      
      // 图3是右下的部分：bottomRight, bottomMid, rightMid
      // 角3在bottomRight顶点，两条边指向bottomMid和rightMid
      const angle3P1 = bottomMid;
      const angle3P2 = rightMid;

      // 绘制角3的弧线
      let a1_3 = Math.atan2(angle3P1.y - angle3Vertex.y, angle3P1.x - angle3Vertex.x);
      let a2_3 = Math.atan2(angle3P2.y - angle3Vertex.y, angle3P2.x - angle3Vertex.x);
      
      // 标准化角度到 [0, 2π)
      if (a1_3 < 0) a1_3 += 2 * Math.PI;
      if (a2_3 < 0) a2_3 += 2 * Math.PI;
      
      // 计算角度差，确保始终取内角
      let angleDiff3 = a2_3 - a1_3;
      if (angleDiff3 < 0) angleDiff3 += 2 * Math.PI;
      const counterclockwise3 = angleDiff3 > Math.PI;
      
      ctx.strokeStyle = '#2196F3';
      ctx.lineWidth = 2;
      ctx.beginPath();
      ctx.arc(angle3Vertex.x, angle3Vertex.y, radius, a1_3, a2_3, counterclockwise3);
      ctx.stroke();

      // 计算内角的中间角度
      let midAngle3;
      if (counterclockwise3) {
        const innerAngleDiff3 = 2 * Math.PI - angleDiff3;
        midAngle3 = a1_3 - innerAngleDiff3 / 2;
      } else {
        midAngle3 = a1_3 + angleDiff3 / 2;
      }
      
      const labelX3 = angle3Vertex.x + Math.cos(midAngle3) * labelRadius;
      const labelY3 = angle3Vertex.y + Math.sin(midAngle3) * labelRadius;
      
      ctx.font = 'bold 18px Arial';
      ctx.fillStyle = '#2196F3';
      ctx.textAlign = 'center';
      ctx.textBaseline = 'middle';
      ctx.fillText('∠3', labelX3, labelY3);

      ctx.restore();
    }

    // 绘制顶点
    // 只在非折叠模式下显示可拖动的顶点（顶部）
    if (!showFoldLines && !showFoldAnimation) {
      ctx.beginPath();
      ctx.arc(top.x, top.y, 8, 0, Math.PI * 2);
      ctx.fillStyle = '#2196F3';
      ctx.fill();
      ctx.strokeStyle = '#fff';
      ctx.lineWidth = 2;
      ctx.stroke();
    }

    // 不再显示固定的顶点（底部两个）

  }, [vertices, angle1, angle2, angle3, showCutLines, showFoldLines, showFoldAnimation, foldProgress, showAssemble, animationProgress]);

  // 获取画布坐标
  const getCanvasCoords = (e) => {
    const canvas = canvasRef.current;
    const rect = canvas.getBoundingClientRect();
    
    const clientX = e.touches ? e.touches[0].clientX : e.clientX;
    const clientY = e.touches ? e.touches[0].clientY : e.clientY;
    
    // 检查是否是小屏幕旋转模式
    const isSmallScreen = window.innerWidth <= 480;
    
    if (isSmallScreen) {
      // 小屏幕旋转模式：容器旋转了90度（顺时针）
      // canvas的getBoundingClientRect()返回的是旋转后在屏幕上的实际位置
      
      // 计算点击位置相对于canvas的位置（在屏幕坐标系中）
      const relativeX = clientX - rect.left;
      const relativeY = clientY - rect.top;
      
      // 旋转90度（顺时针）的逆变换
      // 旋转90度：原坐标(x, y) -> 旋转后(y, -x)
      // 逆变换：旋转后坐标(x', y') -> 原坐标(-y', x')
      // 但由于Y轴方向（向下为正），实际变换为：
      const originalX = relativeY;
      const originalY = rect.width - relativeX;
      
      // 根据当前画布尺寸，将坐标映射回原始工作空间
      // 注意：旋转后canvas的显示宽度是rect.height，高度是rect.width
      const scale = rect.height / WORKSPACE_WIDTH;
      
      return {
        x: originalX / scale,
        y: originalY / scale
      };
    }
    
    // 正常模式：原有逻辑
    // 计算相对于canvas的坐标
    const relativeX = clientX - rect.left;
    const relativeY = clientY - rect.top;
    
    // 根据当前画布尺寸，将坐标映射回原始工作空间
    const windowWidth = window.innerWidth;
    const windowHeight = window.innerHeight;
    const isLandscape = windowWidth > windowHeight;
    const referenceSize = isLandscape ? windowHeight : windowWidth;
    
    let scale = 1;
    
    if (referenceSize <= 375) {
      scale = 360 / WORKSPACE_WIDTH;
    } else if (referenceSize <= 560) {
      const ratio = (referenceSize - 375) / (560 - 375);
      const displayWidth = Math.round(360 + ratio * (560 - 360));
      scale = displayWidth / WORKSPACE_WIDTH;
    }
    
    return {
      x: relativeX / scale,
      y: relativeY / scale
    };
  };

  // 检查是否点击了顶部顶点（与普通画布一致：pointSize(8) + threshold(5) = 13）
  const isClickOnTopVertex = (x, y) => {
    const dx = x - vertices.top.x;
    const dy = y - vertices.top.y;
    return Math.sqrt(dx * dx + dy * dy) < 28;
  };

  // 鼠标按下
  const handleMouseDown = (e) => {
    const coords = getCanvasCoords(e);
    if (isClickOnTopVertex(coords.x, coords.y)) {
      setDragging(true);
    }
  };

  // 鼠标移动
  const handleMouseMove = (e) => {
    if (!dragging) return;
    
    const coords = getCanvasCoords(e);
    
    // 限制顶点在合理范围内（调整范围以适应缩小后的图形）
    const margin = 80;
    const newX = Math.max(margin + 150, Math.min(720 - 150, coords.x));
    const newY = Math.max(margin, Math.min(300, coords.y));
    
    // 先设置新位置
    const newVertices = {
      ...vertices,
      top: { x: newX, y: newY }
    };
    
    // 直接更新位置，不再约束为锐角三角形
    setVertices(newVertices);
  };

  // 鼠标释放
  const handleMouseUp = () => {
    setDragging(false);
  };

  // 重置
  const handleReset = () => {
    setVertices({
      top: { x: 400, y: 150 },
      bottomLeft: { x: 200, y: 380 },
      bottomRight: { x: 600, y: 380 }
    });
    setShowCutLines(false);
    setShowFoldLines(false);
    setShowFoldAnimation(false);
    setFoldProgress(0);
    setShowAssemble(false);
    setAnimationProgress(0);
  };

  // 剪一剪
  const handleCut = () => {
    // 如果正在折叠，不允许剪
    if (showFoldLines || showFoldAnimation) {
      return;
    }
    
    setShowCutLines(!showCutLines);
    if (showCutLines) {
      setShowAssemble(false);
      setAnimationProgress(0);
    }
  };

  // 折一折
  const handleFold = () => {
    // 如果正在剪或拼，不允许折
    if (showCutLines || showAssemble) {
      return;
    }
    
    if (!showFoldLines) {
      // 显示折线和阴影
      setShowFoldLines(true);
      setShowFoldAnimation(false);
      setFoldProgress(0);
    } else if (!showFoldAnimation) {
      // 开始翻折动画
      setShowFoldAnimation(true);
      let progress = 0;
      const animate = () => {
        progress += 0.015;
        if (progress <= 1) {
          setFoldProgress(progress);
          requestAnimationFrame(animate);
        } else {
          setFoldProgress(1);
        }
      };
      animate();
    } else {
      // 重置折叠状态
      setShowFoldLines(false);
      setShowFoldAnimation(false);
      setFoldProgress(0);
    }
  };

  // 拼一拼
  const handleAssemble = () => {
    if (!showCutLines) {
      // 必须先剪一剪
      return;
    }
    
    // 如果正在折叠，不允许拼
    if (showFoldLines || showFoldAnimation) {
      return;
    }
    
    if (!showAssemble) {
      setShowAssemble(true);
      // 开始动画
      let progress = 0;
      const animate = () => {
        progress += 0.02;
        if (progress <= 1) {
          setAnimationProgress(progress);
          requestAnimationFrame(animate);
        } else {
          setAnimationProgress(1);
        }
      };
      animate();
    } else {
      setShowAssemble(false);
      setAnimationProgress(0);
    }
  };

  return (
    <div className="special-model-container">
      {/* 顶部标题栏 */}
      <div className="special-model-top-bar">
        <button
          onClick={() => navigate('/')}
          className="back-button"
          aria-label="返回列表"
        >
          <ArrowLeft size={20} />
          <span className="back-text">返回</span>
        </button>
        <h1 className="app-title">{modelTitle || '三角形内角和'}</h1>
        <img src="/geometry/logo.png" alt="Logo" className="app-logo" />
      </div>

      {/* 主内容区：左中右布局 */}
      <div className="special-model-content">
        {/* 左侧信息面板 */}
        <div className="special-model-info">
          <div className="info-item">
            <span className="info-label">∠1</span>
            <span className="info-equals"> = </span>
            <span className="info-value">{angle1}°</span>
          </div>
          <div className="info-item">
            <span className="info-label">∠2</span>
            <span className="info-equals"> = </span>
            <span className="info-value">{angle2}°</span>
          </div>
          <div className="info-item">
            <span className="info-label">∠3</span>
            <span className="info-equals"> = </span>
            <span className="info-value">{angle3}°</span>
          </div>
        </div>

        {/* 中间画布区 */}
        <div className="special-model-canvas-wrapper">
          <canvas
            ref={canvasRef}
            className="special-model-canvas"
            onMouseDown={handleMouseDown}
            onMouseMove={handleMouseMove}
            onMouseUp={handleMouseUp}
            onMouseLeave={handleMouseUp}
            onTouchStart={handleMouseDown}
            onTouchMove={handleMouseMove}
            onTouchEnd={handleMouseUp}
          />
        </div>

        {/* 右侧控制面板 */}
        <div className="special-model-controls">
          <button
            className="btn"
            onClick={handleCut}
            disabled={showFoldLines || showFoldAnimation}
          >
            {showCutLines ? '取消剪一剪' : '剪一剪'}
          </button>
          <button
            className="btn"
            onClick={handleAssemble}
            disabled={!showCutLines || showFoldLines || showFoldAnimation}
          >
            {showAssemble ? '取消拼一拼' : '拼一拼'}
          </button>
          <button
            className="btn"
            onClick={handleFold}
            disabled={showCutLines || showAssemble}
          >
            {showFoldAnimation ? '重置折叠' : (showFoldLines ? '开始翻折' : '折一折')}
          </button>
          <button
            className="btn"
            onClick={handleReset}
          >
            重置
          </button>
        </div>
      </div>

      {/* 下方信息栏 */}
      <div className="special-model-footer">
        <div className="hint-text">
          拖动顶部顶点改变三角形形状
        </div>
      </div>
    </div>
  );
}

export default TriangleInteriorAngles;

